const { app, BrowserWindow } = require('electron');
const path = require('path');
const fs = require('fs');

// 设置日志文件（打包后方便调试）
const logPath = path.join(app.getPath('userData'), 'app.log');
const logStream = fs.createWriteStream(logPath, { flags: 'a' });

// 重定向 console.log 到文件
const originalLog = console.log;
const originalError = console.error;

console.log = function (...args) {
  const message = args.map(arg => typeof arg === 'object' ? JSON.stringify(arg) : arg).join(' ');
  const timestamp = new Date().toISOString();
  logStream.write(`[${timestamp}] [LOG] ${message}\n`);
  originalLog.apply(console, args);
};

console.error = function (...args) {
  const message = args.map(arg => typeof arg === 'object' ? JSON.stringify(arg) : arg).join(' ');
  const timestamp = new Date().toISOString();
  logStream.write(`[${timestamp}] [ERROR] ${message}\n`);
  originalError.apply(console, args);
};

console.log('=================================');
console.log('Application starting...');
console.log('Log file:', logPath);
console.log('App path:', app.getAppPath());
console.log('Is packaged:', app.isPackaged);
console.log('=================================');

// 导入模块
const { initDatabase } = require('./src/main/database');
const { createWindow } = require('./src/main/window');
const { registerCaseHandlers } = require('./src/main/ipc/case');
const { registerDataHandlers } = require('./src/main/ipc/data');

// 应用准备就绪时初始化
app.whenReady().then(async () => {
  try {
    // 1. 初始化数据库
    // 修改为项目根目录 (响应用户需求)
    const userDataPath = __dirname;
    console.log('User data path (Project Root):', userDataPath);

    await initDatabase(userDataPath);

    // 2. 注册 IPC 处理程序
    const { registerFileHandlers } = require('./src/main/ipc/file');
    registerCaseHandlers(userDataPath);
    registerDataHandlers();
    registerFileHandlers();

    // 3. 创建主窗口
    createWindow();

  } catch (error) {
    console.error('Failed to initialize application:', error);
    // 打包后也能看到错误，不要立即退出
    const { dialog } = require('electron');
    dialog.showErrorBox('启动失败', `应用初始化失败：${error.message}\n\n请查看日志文件获取详细信息。`);
    app.quit();
  }
});

// 所有窗口关闭时退出应用
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});